import platform = require('../common/baseCommon');
import bpCommon = require('../common/bpCommon');
import { baseService } from '../common/baseCommon';
const moduleName = "platform.server";
var https = require('https');
var qs = require('querystring');
var sha1 = require('sha1');
/**
 * 云片网api
 */
var apikey = '20c260c28d4d93bd12371e8589e552bc';
var sms_host = 'sms.yunpian.com';
var send_sms_uri = '/v2/sms/single_send.json';

/**
 * 网易云api
 */
var Appkey = '6295b68a24a448248deff1bf619c1509';
var Nonce = "123456";
var AppSecret = 'a32b80eb579b45da8fc2cb940404cae9';


/** 
 * 发送短信模拟服务接口
*/
@platform.addon("发送短信模拟服务", "发送短信模拟服务", moduleName)
export class smlyunpianService extends baseService implements bpCommon.ISMSPlatform{
    codeinterface?: bpCommon.ISMSPlatform;
    /**
     * 模拟发送短信
     * @param mobile 手机号码
     * @param text 要发送的内容
     */
    sendmessages(mobile: string, text: string) {

    }

    /**
     *送验证码模拟服务
     * @param mobile 手机号码
     * @param tpl_id 模板id
     * @param tpl_value 模板对应内容
     */
    sendverificationcode(mobile: string, tpl_id: number, codeLen: number): Promise<string> {
        var codenumber = "1111";
        return Promise.resolve().then(() => {
            return codenumber;
        })
    }

    /**
     * 发送短信模板模拟服务
     * @param mobile 手机号码
     * @param tpl_id 模板id
     * @param tpl_value 对应模板数据
     */
    sendsmstemplate(mobile: string, tpl_id: number, tpl_value: any) {
    }

    
}
export class yunpianService extends baseService implements bpCommon.ISMSPlatform {

    codeinterface?: bpCommon.ISMSPlatform;
    /**
     * 云片网发送短信
     * @param mobile 手机号码
     * @param text 要发送的内容
     */
    sendmessages(mobile: string, text: string) {
        var post_data = {
            'apikey': apikey,
            'mobile': mobile,
            'text': text,
        };
        var content = qs.stringify(post_data);
        this.post('https://sms.yunpian.com/v2/sms/single_send.json', content, sms_host);

    }

    /**
     * 云片网发送验证码
     * @param mobile 手机号码
     * @param tpl_id 模板id
     * @param tpl_value 模板对应内容
     */
    sendverificationcode(mobile: string, tpl_id: number, codeLen: number): Promise<string> {
        var codenumber = "";
        for (var i = 0; i < codeLen; i++) {
            codenumber += Math.floor(Math.random() * 10);
        }
        var tpl_value = { '#code#': codenumber };
        var post_data = {
            'apikey': apikey,
            'mobile': mobile,
            'tpl_id': tpl_id,
            'tpl_value': qs.stringify(tpl_value),
        };//这是需要提交的数据  
        var content = qs.stringify(post_data);
        this.post('https://sms.yunpian.com/v2/sms/tpl_single_send.json', content, sms_host);
        return Promise.resolve().then(() => {
            return codenumber;
        })
    }

    /**
     * 发送短信模板
     * @param mobile 手机号码
     * @param tpl_id 模板id
     * @param tpl_value 对应模板数据
     */
    sendsmstemplate(mobile: string, tpl_id: number, tpl_value: any) {
        var post_data = {
            'apikey': apikey,
            'mobile': mobile,
            'tpl_id': tpl_id,
            'tpl_value': qs.stringify(tpl_value),
        };
        var content = qs.stringify(post_data);
        this.post('https://sms.yunpian.com/v2/sms/tpl_single_send.json', content, sms_host);

    }

    post(uri, content, host) {
        var options = {
            hostname: host,
            port: 443,
            path: uri,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        };
        var req = https.request(options, function (res) {
            console.log('STATUS: ' + res.statusCode);
            console.log('HEADERS: ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                debugger;
                console.log('BODY: ' + chunk);
            });
        });
        console.log(content);
        req.write(content);
        req.end();
    }
}

@platform.addon("网易云短信平台", "网易云短信平台（可用于远程代理）", moduleName)
export class aliyunService extends baseService implements bpCommon.ISMSPlatform {

    /**
     * 发送手机短信
     * @param mobile 手机号码
     * @param text 对应模板内容
     * @param templateid 模板id
     */
    sendmessages(mobile: string, text: string, templateid: number) {
        let now = Date.now() / 1000;
        let CurTime = parseInt(now + "");
        var path = '/sms/sendtemplate.action';
        var str = AppSecret + Nonce + CurTime;
        var CheckSum = sha1(str);
        var post_data = {
            templateid: templateid,
            mobiles: [mobile],
            params: [text]
        };
        var content = qs.stringify(post_data); //序列化 a=c&name=d  并且将中文字符进行urlencode 编码进行传输  
        console.log(content)
        this.post(path, content, CurTime, CheckSum);
    }
    /**
     * 发送验证码
     * @param mobile 手机号码
     * @param tpl_id 模板id
     * @param codeLen 生成验证码的长度
     */
    sendverificationcode(mobile: string, tpl_id: number, codeLen: number): Promise<string> {
        let now = Date.now() / 1000;
        let CurTime = parseInt(now + "");
        var str = AppSecret + Nonce + CurTime;
        var CheckSum = sha1(str);
        var codenumber = "";
        var post_data = {
            templateid: tpl_id,
            mobiles: mobile,
            codeLen: codeLen
        };
        var content = qs.stringify(post_data);
        var options = {
            hostname: 'api.netease.im',
            //port:443,  
            path: '/sms/sendcode.action',
            method: 'POST',
            headers: {
                'AppKey': Appkey,
                'Nonce': Nonce,
                'CurTime': CurTime,
                'CheckSum': CheckSum,
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',

            }
        };
        var req = https.request(options, function (res) {
            console.log('STATUS: ' + res.statusCode);
            //console.log('HEADERS: '+res.headers);    
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                codenumber = JSON.parse(chunk).obj
                console.log('BODY: ' + chunk);
            });
        });
        req.on('error', function (e) {
            console.log('problem with request: ' + e.message);
        });
        req.write(content);
        req.end();
        return Promise.resolve().then(() => {
            return codenumber;
        })
    }
    /**
     * 发送短信模板
     * @param mobile 手机号码
     * @param tpl_id 模板id
     * @param tpl_value 对应模板数据
     */
    sendsmstemplate(mobile: string, tpl_id: number, tpl_value: any) {
        let now = Date.now() / 1000;
        let CurTime = parseInt(now + "");
        var path = '/sms/sendtemplate.action';
        var str = AppSecret + Nonce + CurTime;
        var CheckSum = sha1(str);
        var post_data = {
            templateid: tpl_id,
            mobiles: [mobile],
            params: [tpl_value]
        };
        var content = qs.stringify(post_data); //序列化 a=c&name=d  并且将中文字符进行urlencode 编码进行传输  
        console.log(content)
        this.post(path, content, CurTime, CheckSum);
    }

    post(path, content, CurTime, CheckSum) {
        var options = {
            hostname: 'api.netease.im',
            //port:443,  
            path: path,
            method: 'POST',
            headers: {
                'AppKey': Appkey,
                'Nonce': Nonce,
                'CurTime': CurTime,
                'CheckSum': CheckSum,
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',

            }
        };
        var req = https.request(options, function (res) {
            console.log('STATUS: ' + res.statusCode);
            //console.log('HEADERS: '+res.headers);    
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                console.log('BODY: ' + chunk);
            });
        });
        req.on('error', function (e) {
            console.log('problem with request: ' + e.message);
        });
        req.write(content);
        req.end();

    }
}
